/*
 * Copyright 2012 - 2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.solr.showcase.product.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.solr.showcase.product.ProductRepository;
import org.springframework.data.solr.showcase.product.ProductService;
import org.springframework.data.solr.showcase.product.model.Product;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Christoph Strobl
 * @param <ProductRepository>
 */
@Controller
@Component
@Scope("prototype")
public class ProductController {

	@Autowired
	private ProductService productService;
	
	
	@Autowired
	private ProductRepository productRepository;
	
	@RequestMapping("/product/{id}")
	public String search(Model model, @PathVariable("id") String id, HttpServletRequest request) {
		model.addAttribute("product", productService.findById(id));
		return "product";
	}

	
	@RequestMapping("/product/save")
	public String save(Model model, HttpServletRequest request) {
		model.addAttribute("product", productRepository.save(createProductList(20)));
		return "product";
	}

	
	
	
	 protected List<Product> createProductList(int nrProducts) {
		    List<Product> products = new ArrayList<Product>(nrProducts);
		    for (int i = 0; i < nrProducts; i++) {
		      products.add(createProduct(i));
		    }
		    return products;
		  }

		  protected Product createProduct(int id) {
		    Product product = new Product();
		    product.setId(Integer.toString(id));
		    product.setAvailable(id % 2 == 0);
		    product.setName("product-" + id);
		    product.setPopularity(id * 10);
		    product.setPrice((float) id * 100);
		    return product;
		  }
	
	
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

}
